package org.wannatrak.android.activity;

import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Looper;
import android.text.method.PasswordTransformationMethod;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.TextView;
import org.wannatrak.android.ApplicationContext;
import org.wannatrak.android.R;
import org.wannatrak.android.entity.Credential;
import org.wannatrak.android.exceptions.HttpException;
import org.wannatrak.android.helper.DialogHelper;
import org.wannatrak.android.helper.UIHelper;
import org.wannatrak.android.intf.ClickAction;
import org.wannatrak.android.intf.DialogAction;

public class StartPageActivity extends AbstractContextMenuActivity {

    /**
     * thread for executing async login
     */
    private Thread t;

    /**
     * dialog that shows async execution
     */
    private Dialog dialog;

    /**
     * Called when the activity is first created.
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ApplicationContext.init(this);
        setContentView(R.layout.start_page);
        init();
    }

    @Override
    protected void onStart() {
        super.onStart();
        if (checkRememberMe()) {
            if (loadCredentials()) {
                login(ApplicationContext.getSettingService().loadSetting("login"),
                        ApplicationContext.getSettingService().loadSetting("password"));
            } else {
                //it is impossible
            }
        }
    }

    @Override
    public Object onRetainNonConfigurationInstance() {
        if (dialog != null && dialog.isShowing()) {
            dialog.dismiss();
        }
        return super.onRetainNonConfigurationInstance();
    }

    private boolean checkRememberMe() {
        String s = ApplicationContext.getSettingService().loadSetting("rememberMe");
        return Boolean.parseBoolean(s);
    }

    private void init() {

        if (!UIHelper.isOnline(StartPageActivity.this)) {
            UIHelper.closeSoftInput(StartPageActivity.this);
            DialogHelper.showNoInternetDialog(StartPageActivity.this, new DialogAction() {
                public void actionPerformed(DialogInterface di, int code) {
                    di.dismiss();
                }

                public int getNameCode() {
                    return R.string.skip;
                }
            });
        }
        UIHelper.setActionToView(findViewById(R.id.helpButton), new ClickAction() {
            public boolean actionPerformed(View view) {
                openHelp();
                return true;
            }
        });

        UIHelper.setActionToView(findViewById(R.id.loginButton), new ClickAction() {
            public boolean actionPerformed(View view) {
                final String login = ((TextView) findViewById(R.id.login)).getText().toString();
                final String password = ((TextView) findViewById(R.id.password)).getText().toString();
                String validateResult = validate(login, password);
                if (validateResult != null) {
                    UIHelper.createAlertDialog(StartPageActivity.this, validateResult, -1, true, null).show();
                    return true;
                }

                login(login, password);
                boolean rememberMe = ((CheckBox) findViewById(R.id.checkBox)).isChecked();
                ApplicationContext.getSettingService().saveSetting("rememberMe", String.valueOf(rememberMe));
                return true;
            }
        });

        CheckBox view = (CheckBox) findViewById(R.id.showPasswordBox);
        view.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                initPasswordField(b);
            }
        });
    }

    private void login(final String login, final String password) {
        dialog = DialogHelper.createProgressDialog(StartPageActivity.this);
        final DialogHandler handler = new DialogHandler(dialog, StartPageActivity.this);
        dialog.show();
        Runnable r = new Runnable() {
            public void run() {
                Looper.prepare();
                try {
                    if (ApplicationContext.getWannatrakService().login(login, password)) {
                        startActivity(new Intent(StartPageActivity.this, SettingActivity.class));
                        finish();
                    }
                } catch (HttpException e) {
                    handler.sendMessage(handler.obtainMessage(-1234, e.getMessage()));
                } finally {
                    dialog.dismiss();
                }
            }
        };
        t = new Thread(r);
        t.start();

    }

    private String validate(String login, String password) {
        if (login == null || "".equals(login.trim())) {
            return getString(R.string.err_login_empty);
        }

        if (password == null || "".equals(password.trim())) {
            return getString(R.string.err_password_empty);
        }

        return null;
    }

    private boolean loadCredentials() {
        Cursor c = getContentResolver().query(Credential.CONTENT_URI, null, null, null, Credential._ID + " desc");
        try {
            if (c.moveToFirst()) {
                ApplicationContext.getSettingService().saveSetting("login", c.getString(c.getColumnIndex(Credential.LOGIN)));
                ApplicationContext.getSettingService().saveSetting("password", c.getString(c.getColumnIndex(Credential.PASSWORD)));
                ApplicationContext.getSettingService().saveSetting("deviceKey", c.getString(c.getColumnIndex(Credential.DEVICE_KEY)));
                return true;
            } else {
                return false;
            }
        } finally {
            c.close();
        }
    }

    private void initPasswordField(boolean showPassword) {
        EditText view = (EditText) findViewById(R.id.password);
        if (showPassword) {
            view.setTransformationMethod(null);
        } else {
            view.setTransformationMethod(new PasswordTransformationMethod());
        }
    }
}
